package ui.activity.user_managament;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.googlecode.mp4parser.authoring.tracks.TextTrackImpl;
import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;
import com.wefika.flowlayout.FlowLayout;

import java.util.ArrayList;
import java.util.HashMap;

import adapter.user_management.SuggestUserInInviteUserToCompanyAdapter;
import controller.user_management.GetUserInfoFromContactAsync;
import controller.user_management.InviteUserToCompanyAsync;
import custom_view.InviteUserTabLinearLayout;
import ui.activity.login.Login;
import utils.Utils;

/**
 * Created by Dong Le on 6/19/2015.
 */
public class InviteUserToCompany extends Activity implements View.OnClickListener, View.OnTouchListener {

    //string session
    public Boolean HAS_ALREADY_GET_DATA_FROM_CONTACT = false;
    //View session
    public static EditText mEtInputUserEmail;
    private LinearLayout mLlInInviteUserToCompany;
    public static ListView mLvSuggestUserInInviteUserToCompany;
    private TextView mTvCancelInInviteUserToCompany;
    public static TextView mTvInviteInInviteUserToCompany;
    public static FlowLayout mflowlayoutInInviteUserToCompany;
    public static ArrayList <String> mAlInviteUserEmail = new ArrayList<>();
    //the others session
    public static Context mContext;
    public  static SuggestUserInInviteUserToCompanyAdapter suggestUserInInviteUserToCompanyAdapter;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_invite_in_invite_user_to_company_activity:
                if (mAlInviteUserEmail.size() > 0) {
                    String USER_EMAILS = "";
                    for (int i = 0; i < mAlInviteUserEmail.size(); i++) {
                        USER_EMAILS = USER_EMAILS + mAlInviteUserEmail.get(i) + ",";
                    }
                    USER_EMAILS = USER_EMAILS.substring(0 ,USER_EMAILS.length() - 1);
                    Log.i("","USER_EMAILS " + USER_EMAILS);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        new InviteUserToCompanyAsync(mContext).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                                String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                                USER_EMAILS,
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyId()
                                ),
                                Enterprise.company.getCompanyNameSelected(),
                                mContext.getResources().getString(R.string.general_user));
                    else
                        new InviteUserToCompanyAsync(mContext).execute(
                                String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                                USER_EMAILS,
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyId()
                                ),
                                Enterprise.company.getCompanyNameSelected(),
                                mContext.getResources().getString(R.string.general_user));
                    //disable text view invite user to company, avoid user click much times
                    mTvInviteInInviteUserToCompany.setEnabled(false);
                }

                break;
            case R.id.tv_cancel_in_invite_user_to_company_activity:
                //reset array email
                if (!mAlInviteUserEmail.isEmpty()) {
                    mAlInviteUserEmail.clear();
                }
                //reset data array check box checked
                if (!SuggestUserInInviteUserToCompanyAdapter.mAlPosOfItemCheckedInSuggestUser.isEmpty())
                    SuggestUserInInviteUserToCompanyAdapter.mAlPosOfItemCheckedInSuggestUser.clear();
                finish();
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_user_to_company);
        mContext = this;
        initialViews();
        initialData();
        addInviteUserTab();
//        getNameEmailDetails();
        // user async task this call: avoid delay get many data.
//        Log.i("","getContacts() " + getContacts());
        if (!HAS_ALREADY_GET_DATA_FROM_CONTACT) {
            Log.i("","GET CONTACT");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                new GetUserInfoFromContactAsync(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                new GetUserInfoFromContactAsync(this).execute();
            HAS_ALREADY_GET_DATA_FROM_CONTACT = true;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent motionEvent) {
        switch (v.getId()) {
            case R.id.ll_in_invite_user_to_company_activity:
                Utils.hideSoftKeyboard(mContext, mEtInputUserEmail);
                break;
        }
        return false;
    }

    private void initialData() {
        mTvInviteInInviteUserToCompany.setOnClickListener(this);
        mTvCancelInInviteUserToCompany.setOnClickListener(this);
        mLlInInviteUserToCompany.setOnTouchListener(this);

        if (GetUserInfoFromContactAsync.mAlUserInfoFromContact != null) {
            InviteUserToCompany.suggestUserInInviteUserToCompanyAdapter = new SuggestUserInInviteUserToCompanyAdapter(
                    mContext, R.layout.simple_list_item_in_suggest_user_in_invite_user_to_company_activity,
                    GetUserInfoFromContactAsync.mAlUserInfoFromContact
            );
            InviteUserToCompany.mLvSuggestUserInInviteUserToCompany.setAdapter(
                    InviteUserToCompany.suggestUserInInviteUserToCompanyAdapter
            );
        }
    }
    private void initialViews() {
        mLlInInviteUserToCompany = (LinearLayout) findViewById(R.id.ll_in_invite_user_to_company_activity);
        mLvSuggestUserInInviteUserToCompany = (ListView) findViewById(R.id.lv_suggest_user_in_invite_user_to_company_activity);
        mTvInviteInInviteUserToCompany = (TextView) findViewById(R.id.tv_invite_in_invite_user_to_company_activity);
        mTvCancelInInviteUserToCompany = (TextView) findViewById(R.id.tv_cancel_in_invite_user_to_company_activity);
        mflowlayoutInInviteUserToCompany = (FlowLayout) findViewById(R.id.flowlayout_in_invite_user_to_company_activity);
        // add edit text input user to flow layout invite user to company
        mEtInputUserEmail = new EditText(this);
        mEtInputUserEmail.setBackgroundColor(getResources().getColor(R.color.transparent));
        mEtInputUserEmail.setHint(mContext.getString(R.string.email_address));
        FlowLayout.LayoutParams layoutParamsForEditTextInputUserEmail = new FlowLayout.LayoutParams(
                FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.MATCH_PARENT
        );
        layoutParamsForEditTextInputUserEmail.gravity = Gravity.CENTER;
        mEtInputUserEmail.setLayoutParams(layoutParamsForEditTextInputUserEmail);
        mflowlayoutInInviteUserToCompany.addView(mEtInputUserEmail);
    }

    //the others method
    private void addInviteUserTab() {
        //set done soft keyboard for mEtInputUserEmail
        mEtInputUserEmail.setSingleLine(true);
        mEtInputUserEmail.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                switch (actionId) {
                    case EditorInfo.IME_ACTION_DONE:
                        //check mail empty, mail valid and mail existed
                        if (!Utils.checkFillBlank(mEtInputUserEmail) &&
                                Utils.isEmailValid(mEtInputUserEmail) &&
                                !mAlInviteUserEmail.contains(mEtInputUserEmail.getText().toString())) {
                            mAlInviteUserEmail.add(mEtInputUserEmail.getText().toString());

                            //add the latest new mail in array to flow layout
                            //add to position ahead position of edit text input mail
                            mflowlayoutInInviteUserToCompany.addView(
                                    InviteUserTabLinearLayout.newInstance(
                                            mContext, mAlInviteUserEmail.get(mAlInviteUserEmail.size() - 1)),
                                    mflowlayoutInInviteUserToCompany.getChildCount() - 1);
                            //set flag for each tab ==  position data of tab in array
                            mflowlayoutInInviteUserToCompany.
                                    getChildAt(mAlInviteUserEmail.size() - 1).
                                    setTag(mAlInviteUserEmail.size() - 1);
                            //clear text after input email success
                            mEtInputUserEmail.setText("");
                            //set text for mTvInviteInInviteUserToCompany
                            setTextForTextViewInviteInInviteUserToCompany(mAlInviteUserEmail);
                        } else {
                            Toast.makeText(getApplicationContext(), mContext.getString(R.string.toast_check_email_in_edit_text),
                                    Toast.LENGTH_LONG).show();
                        }
                        break;
                    case EditorInfo.IME_ACTION_NONE:
                        break;
                }
                return false;
            }
        });
    }

    //set text for mTvInviteInInviteUserToCompany
    public static void setTextForTextViewInviteInInviteUserToCompany(ArrayList <String> mAlinviteUserEmail) {
        if (mAlinviteUserEmail.size() > 0) {
            mTvInviteInInviteUserToCompany.setText(
                    mContext.getString(R.string.invite) + "(" +
                            String.valueOf(mAlinviteUserEmail.size()) + ")"
            );
            mTvInviteInInviteUserToCompany.setTextColor(
                    mContext.getResources().getColor(R.color.orange)
            );
            mTvInviteInInviteUserToCompany.setEnabled(true);
        } else {
            mTvInviteInInviteUserToCompany.setText(mContext.getString(R.string.invite));
            mTvInviteInInviteUserToCompany.setTextColor(
                    mContext.getResources().getColor(R.color.gray)
            );
            mTvInviteInInviteUserToCompany.setEnabled(false);
        }
    }

//    public ArrayList<String> getNameEmailDetails() {
//        ArrayList<String> names = new ArrayList<>();
//        ContentResolver cr = getContentResolver();
//        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
//        if (cur.getCount() > 0) {
//            while (cur.moveToNext()) {
//                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
//                Cursor cur1 = cr.query(
//                        ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
//                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
//                        new String[]{id}, null);
//                while (cur1.moveToNext()) {
//                    //to get the contact names
//                    String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
//                    Log.i("Name :", name);
//                    String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
//                    Log.i("Email", email);
//                    if(email!=null){
//                        names.add(name);
//                    }
//                }
//                cur1.close();
//            }
//        }
//        return names;
//    }

}
